// 无障碍工具类
// 提供ARIA属性、键盘操作、焦点管理等辅助功能

import { accessibilityService } from '../plugins/accessibility/AccessibilityService';

// ARIA角色常量
export const ARIA_ROLES = {
  // 文档结构角色
  ARTICLE: 'article',
  ASIDE: 'aside',
  BANNER: 'banner',
  COMPLEMENTARY: 'complementary',
  CONTENTINFO: 'contentinfo',
  DEFINITION: 'definition',
  DIALOG: 'dialog',
  DOCUMENT: 'document',
  FEED: 'feed',
  FIGURE: 'figure',
  FOOTER: 'contentinfo',
  FORM: 'form',
  HEADER: 'banner',
  MAIN: 'main',
  MATH: 'math',
  NAV: 'navigation',
  NOTE: 'note',
  REGION: 'region',
  SEARCH: 'search',
  
  // 交互角色
  ALERT: 'alert',
  ALERTDIALOG: 'alertdialog',
  BUTTON: 'button',
  CHECKBOX: 'checkbox',
  COMBOBOX: 'combobox',
  GRID: 'grid',
  GRIDCELL: 'gridcell',
  GROUP: 'group',
  LINK: 'link',
  LISTBOX: 'listbox',
  MENU: 'menu',
  MENUITEM: 'menuitem',
  MENUITEMCHECKBOX: 'menuitemcheckbox',
  MENUITEMRADIO: 'menuitemradio',
  OPTION: 'option',
  POPUPMENU: 'menu',
  RADIO: 'radio',
  RADIOGROUP: 'radiogroup',
  SCROLLBAR: 'scrollbar',
  SELECT: 'select',
  SEPARATOR: 'separator',
  SLIDER: 'slider',
  SPINBUTTON: 'spinbutton',
  STATUS: 'status',
  TAB: 'tab',
  TABLIST: 'tablist',
  TABPANEL: 'tabpanel',
  TEXTBOX: 'textbox',
  TOOLBAR: 'toolbar',
  TOOLTIP: 'tooltip',
  TREE: 'tree',
  TREEITEM: 'treeitem',
  TREEgrid: 'treegrid',
  
  // 结构角色
  CAPTIONSIDE: 'captionside',
  CELL: 'cell',
  COL: 'columnheader',
  COLGROUP: 'columnheader',
  DEFINITION: 'definition',
  DIRECTORY: 'directory',
  DOCUMENTFRAGMENT: 'document-fragment',
  DOCUMENTTYPE: 'document-type',
  FIELDSET: 'group',
  FIGCAPTION: 'figure-caption',
  FOOTER: 'contentinfo',
  H1: 'heading',
  H2: 'heading',
  H3: 'heading',
  H4: 'heading',
  H5: 'heading',
  H6: 'heading',
  HR: 'separator',
  LABEL: 'label',
  LEGEND: 'group',
  LI: 'listitem',
  LIST: 'list',
  METER: 'meter',
  OL: 'list',
  OPTGROUP: 'group',
  OUTPUT: 'status',
  P: 'paragraph',
  PRE: 'paragraph',
  PROGRESSBAR: 'progressbar',
  Q: 'blockquote',
  ROW: 'row',
  ROWGROUP: 'rowgroup',
  ROWHEADER: 'rowheader',
  TABLE: 'table',
  TBODY: 'rowgroup',
  TD: 'cell',
  TFOOT: 'rowgroup',
  TH: 'columnheader',
  THEAD: 'rowgroup',
  TR: 'row',
  UL: 'list'
};

// ARIA状态和属性常量
export const ARIA_ATTRIBUTES = {
  // 状态属性
  BUSY: 'aria-busy',
  CHECKED: 'aria-checked',
  DISABLED: 'aria-disabled',
  EXPANDED: 'aria-expanded',
  HIDDEN: 'aria-hidden',
  INVALID: 'aria-invalid',
  LIVE: 'aria-live',
  MODAL: 'aria-modal',
  MULTILINE: 'aria-multiline',
  MULTISELECTABLE: 'aria-multiselectable',
  ORIENTATION: 'aria-orientation',
  PRESSED: 'aria-pressed',
  READONLY: 'aria-readonly',
  REQUIRED: 'aria-required',
  SELECTED: 'aria-selected',
  
  // 关系属性
  ACTIVEDESCENDANT: 'aria-activedescendant',
  CONTROLS: 'aria-controls',
  DESCRIBEDBY: 'aria-describedby',
  DETAILS: 'aria-details',
  ERRORMESSAGE: 'aria-errormessage',
  FLOWTO: 'aria-flowto',
  LABELLEDBY: 'aria-labelledby',
  OWNS: 'aria-owns',
  POSINSET: 'aria-posinset',
  SETSIZE: 'aria-setsize',
  
  // 其他属性
  AUTOCOMPLETE: 'aria-autocomplete',
  COLS: 'aria-cols',
  CURRENT: 'aria-current',
  DESCRIPTION: 'aria-description',
  DROPEFFECT: 'aria-dropeffect',
  GRABBED: 'aria-grabbed',
  HASPOPUP: 'aria-haspopup',
  KEYSHORTCODES: 'aria-keyshortcuts',
  LABEL: 'aria-label',
  LEVEL: 'aria-level',
  LINKS: 'aria-links',
  LIVE: 'aria-live',
  MAX: 'aria-max',
  MAXVALUE: 'aria-valuemax',
  MIN: 'aria-min',
  MINVALUE: 'aria-valuemin',
  MODEL: 'aria-model',
  PLACEHOLDER: 'aria-placeholder',
  POSINSET: 'aria-posinset',
  ROWCOUNT: 'aria-rowcount',
  ROWINDEX: 'aria-rowindex',
  ROWSPAN: 'aria-rowspan',
  ROLEDESCRIPTION: 'aria-roledescription',
  SORT: 'aria-sort',
  SPAN: 'aria-colspan',
  STATINGROUP: 'aria-owns',
  VALUE: 'aria-valuenow',
  VALUETEXT: 'aria-valuetext',
  
  // 行为属性
  ATOMIC: 'aria-atomic',
  RELEVANT: 'aria-relevant',
  LIVEASSERTIVENESS: 'aria-live',
  DROPEFFECT: 'aria-dropeffect',
  HASPOPUP: 'aria-haspopup'
};

// 键盘键码常量
export const KEY_CODES = {
  // 字母和数字键
  A: 'KeyA',
  B: 'KeyB',
  C: 'KeyC',
  D: 'KeyD',
  E: 'KeyE',
  F: 'KeyF',
  G: 'KeyG',
  H: 'KeyH',
  I: 'KeyI',
  J: 'KeyJ',
  K: 'KeyK',
  L: 'KeyL',
  M: 'KeyM',
  N: 'KeyN',
  O: 'KeyO',
  P: 'KeyP',
  Q: 'KeyQ',
  R: 'KeyR',
  S: 'KeyS',
  T: 'KeyT',
  U: 'KeyU',
  V: 'KeyV',
  W: 'KeyW',
  X: 'KeyX',
  Y: 'KeyY',
  Z: 'KeyZ',
  ZERO: 'Digit0',
  ONE: 'Digit1',
  TWO: 'Digit2',
  THREE: 'Digit3',
  FOUR: 'Digit4',
  FIVE: 'Digit5',
  SIX: 'Digit6',
  SEVEN: 'Digit7',
  EIGHT: 'Digit8',
  NINE: 'Digit9',
  
  // 功能键
  F1: 'F1',
  F2: 'F2',
  F3: 'F3',
  F4: 'F4',
  F5: 'F5',
  F6: 'F6',
  F7: 'F7',
  F8: 'F8',
  F9: 'F9',
  F10: 'F10',
  F11: 'F11',
  F12: 'F12',
  
  // 方向键
  UP: 'ArrowUp',
  DOWN: 'ArrowDown',
  LEFT: 'ArrowLeft',
  RIGHT: 'ArrowRight',
  
  // 特殊键
  TAB: 'Tab',
  ENTER: 'Enter',
  ESCAPE: 'Escape',
  SPACE: ' ',
  BACKSPACE: 'Backspace',
  DELETE: 'Delete',
  INSERT: 'Insert',
  HOME: 'Home',
  END: 'End',
  PAGE_UP: 'PageUp',
  PAGE_DOWN: 'PageDown',
  
  // 修饰键
  SHIFT: 'Shift',
  CONTROL: 'Control',
  ALT: 'Alt',
  META: 'Meta',
  CAPS_LOCK: 'CapsLock',
  
  // 其他键
  PRINT_SCREEN: 'PrintScreen',
  SCROLL_LOCK: 'ScrollLock',
  PAUSE: 'Pause',
  NUM_LOCK: 'NumLock',
  
  // 数字键盘
  NUMPAD0: 'Numpad0',
  NUMPAD1: 'Numpad1',
  NUMPAD2: 'Numpad2',
  NUMPAD3: 'Numpad3',
  NUMPAD4: 'Numpad4',
  NUMPAD5: 'Numpad5',
  NUMPAD6: 'Numpad6',
  NUMPAD7: 'Numpad7',
  NUMPAD8: 'Numpad8',
  NUMPAD9: 'Numpad9',
  NUMPAD_MULTIPLY: 'NumpadMultiply',
  NUMPAD_ADD: 'NumpadAdd',
  NUMPAD_SUBTRACT: 'NumpadSubtract',
  NUMPAD_DECIMAL: 'NumpadDecimal',
  NUMPAD_DIVIDE: 'NumpadDivide',
  NUMPAD_ENTER: 'NumpadEnter'
};

// 无障碍辅助工具类
class AccessibilityUtils {
  constructor() {
    this.focusableElements = [
      'a[href]',
      'area[href]',
      'input:not([disabled])',
      'select:not([disabled])',
      'textarea:not([disabled])',
      'button:not([disabled])',
      '[tabindex]:not([tabindex="-1"])',
      '[contenteditable]',
      'video[controls]',
      'audio[controls]',
      '[role="button"]:not([disabled])',
      '[role="link"]',
      '[role="checkbox"]:not([aria-disabled="true"])',
      '[role="radio"]:not([aria-disabled="true"])',
      '[role="combobox"]:not([aria-disabled="true"])',
      '[role="slider"]:not([aria-disabled="true"])',
      '[role="spinbutton"]:not([aria-disabled="true"])',
      '[role="progressbar"]',
      '[role="tree"]:not([aria-disabled="true"])',
      '[role="grid"]:not([aria-disabled="true"])',
      '[role="dialog"]',
      '[role="menu"]:not([aria-disabled="true"])',
      '[role="tablist"]:not([aria-disabled="true"])',
      '[role="listbox"]:not([aria-disabled="true"])',
      '[role="radiogroup"]:not([aria-disabled="true"])',
      '[role="application"]:not([aria-disabled="true"])',
      '[role="document"]:not([aria-disabled="true"])',
      '[role="article"]:not([aria-disabled="true"])',
      '[role="region"]:not([aria-disabled="true"])',
      '[role="complementary"]:not([aria-disabled="true"])',
      '[role="contentinfo"]:not([aria-disabled="true"])',
      '[role="main"]:not([aria-disabled="true"])',
      '[role="navigation"]:not([aria-disabled="true"])',
      '[role="search"]:not([aria-disabled="true"])',
      '[role="banner"]:not([aria-disabled="true"])',
      '[role="alert"]',
      '[role="status"]',
      '[role="tooltip"]',
      '[role="figure"]:not([aria-disabled="true"])',
      '[role="form"]:not([aria-disabled="true"])',
      '[role="list"]:not([aria-disabled="true"])',
      '[role="listitem"]:not([aria-disabled="true"])',
      '[role="group"]:not([aria-disabled="true"])',
      '[role="separator"]:not([aria-disabled="true"])',
      '[role="scrollbar"]',
      '[role="tab"]:not([aria-disabled="true"])',
      '[role="tabpanel"]:not([aria-disabled="true"])',
      '[role="treeitem"]:not([aria-disabled="true"])',
      '[role="treegrid"]:not([aria-disabled="true"])',
      '[role="option"]:not([aria-disabled="true"])',
      '[role="menuitem"]:not([aria-disabled="true"])',
      '[role="menuitemcheckbox"]:not([aria-disabled="true"])',
      '[role="menuitemradio"]:not([aria-disabled="true"])',
      '[role="command"]:not([aria-disabled="true"])',
      '[role="heading"]:not([aria-disabled="true"])',
      '[role="img"]',
      '[role="math"]:not([aria-disabled="true"])',
      '[role="document-fragment"]:not([aria-disabled="true"])',
      '[role="document-type"]:not([aria-disabled="true"])',
      '[role="directory"]:not([aria-disabled="true"])',
      '[role="definition"]:not([aria-disabled="true"])',
      '[role="figure-caption"]:not([aria-disabled="true"])',
      '[role="legend"]:not([aria-disabled="true"])',
      '[role="meter"]:not([aria-disabled="true"])',
      '[role="ol"]:not([aria-disabled="true"])',
      '[role="optgroup"]:not([aria-disabled="true"])',
      '[role="output"]:not([aria-disabled="true"])',
      '[role="p"]:not([aria-disabled="true"])',
      '[role="pre"]:not([aria-disabled="true"])',
      '[role="q"]:not([aria-disabled="true"])',
      '[role="summary"]:not([aria-disabled="true"])',
      '[role="sup"]:not([aria-disabled="true"])',
      '[role="sub"]:not([aria-disabled="true"])',
      '[role="table"]:not([aria-disabled="true"])',
      '[role="tbody"]:not([aria-disabled="true"])',
      '[role="td"]:not([aria-disabled="true"])',
      '[role="tfoot"]:not([aria-disabled="true"])',
      '[role="th"]:not([aria-disabled="true"])',
      '[role="thead"]:not([aria-disabled="true"])',
      '[role="tr"]:not([aria-disabled="true"])',
      '[role="ul"]:not([aria-disabled="true"])'
    ];
  }
  
  // 设置元素的ARIA属性
  setAriaAttributes(element, attributes) {
    if (!element || typeof attributes !== 'object') return;
    
    Object.entries(attributes).forEach(([key, value]) => {
      const ariaKey = key.startsWith('aria-') ? key : `aria-${key}`;
      
      if (value === null || value === undefined || value === false) {
        element.removeAttribute(ariaKey);
      } else {
        element.setAttribute(ariaKey, value.toString());
      }
    });
    
    return element;
  }
  
  // 获取元素的ARIA属性
  getAriaAttributes(element, attributes) {
    if (!element || !attributes) return {};
    
    const result = {};
    const attributeArray = Array.isArray(attributes) ? attributes : [attributes];
    
    attributeArray.forEach(attr => {
      const ariaAttr = attr.startsWith('aria-') ? attr : `aria-${attr}`;
      result[attr] = element.getAttribute(ariaAttr);
    });
    
    return result;
  }
  
  // 设置元素的角色
  setRole(element, role) {
    if (!element || !role) return element;
    
    element.setAttribute('role', role);
    return element;
  }
  
  // 获取元素的角色
  getRole(element) {
    if (!element) return null;
    
    return element.getAttribute('role');
  }
  
  // 设置元素的标签
  setAriaLabel(element, label) {
    return this.setAriaAttributes(element, { label });
  }
  
  // 设置元素的描述
  setAriaDescription(element, description) {
    return this.setAriaAttributes(element, { description });
  }
  
  // 设置元素的可见性
  setAriaHidden(element, hidden) {
    return this.setAriaAttributes(element, { hidden: hidden ? 'true' : 'false' });
  }
  
  // 设置元素的选中状态
  setAriaSelected(element, selected) {
    return this.setAriaAttributes(element, { selected: selected ? 'true' : 'false' });
  }
  
  // 设置元素的展开状态
  setAriaExpanded(element, expanded) {
    return this.setAriaAttributes(element, { expanded: expanded ? 'true' : 'false' });
  }
  
  // 设置元素的禁用状态
  setAriaDisabled(element, disabled) {
    return this.setAriaAttributes(element, { disabled: disabled ? 'true' : 'false' });
  }
  
  // 设置元素的错误消息
  setAriaErrorMessage(element, errorMessage) {
    return this.setAriaAttributes(element, { errormessage: errorMessage });
  }
  
  // 设置元素的无效状态
  setAriaInvalid(element, invalid) {
    return this.setAriaAttributes(element, { invalid: invalid ? 'true' : 'false' });
  }
  
  // 设置元素的必需状态
  setAriaRequired(element, required) {
    return this.setAriaAttributes(element, { required: required ? 'true' : 'false' });
  }
  
  // 设置元素的只读状态
  setAriaReadonly(element, readonly) {
    return this.setAriaAttributes(element, { readonly: readonly ? 'true' : 'false' });
  }
  
  // 设置元素的检查状态
  setAriaChecked(element, checked) {
    let value = 'false';
    if (checked === true) value = 'true';
    else if (checked === 'mixed' || checked === 'indeterminate') value = 'mixed';
    
    return this.setAriaAttributes(element, { checked: value });
  }
  
  // 设置元素的按下状态
  setAriaPressed(element, pressed) {
    let value = 'false';
    if (pressed === true) value = 'true';
    else if (pressed === 'mixed') value = 'mixed';
    
    return this.setAriaAttributes(element, { pressed: value });
  }
  
  // 设置元素的当前状态
  setAriaCurrent(element, current) {
    return this.setAriaAttributes(element, { current });
  }
  
  // 设置元素的值范围
  setAriaValue(element, min, max, now, text) {
    const attributes = {};
    if (min !== undefined) attributes.valuemin = min;
    if (max !== undefined) attributes.valuemax = max;
    if (now !== undefined) attributes.valuenow = now;
    if (text !== undefined) attributes.valuetext = text;
    
    return this.setAriaAttributes(element, attributes);
  }
  
  // 设置元素的位置信息
  setAriaPosition(element, posInSet, setSize) {
    const attributes = {};
    if (posInSet !== undefined) attributes.posinset = posInSet;
    if (setSize !== undefined) attributes.setsize = setSize;
    
    return this.setAriaAttributes(element, attributes);
  }
  
  // 创建实时区域
  createLiveRegion(parent, options = {}) {
    const { 
      id = `live-region-${Date.now()}`,
      role = 'status',
      live = 'polite',
      atomic = 'false',
      relevant = 'additions text'
    } = options;
    
    const liveRegion = document.createElement('div');
    liveRegion.id = id;
    liveRegion.setAttribute('role', role);
    liveRegion.setAttribute('aria-live', live);
    liveRegion.setAttribute('aria-atomic', atomic);
    liveRegion.setAttribute('aria-relevant', relevant);
    liveRegion.style.position = 'absolute';
    liveRegion.style.width = '1px';
    liveRegion.style.height = '1px';
    liveRegion.style.margin = '-1px';
    liveRegion.style.padding = '0';
    liveRegion.style.border = '0';
    liveRegion.style.overflow = 'hidden';
    liveRegion.style.clamp = '0 0 auto';
    
    if (parent) {
      parent.appendChild(liveRegion);
    }
    
    return liveRegion;
  }
  
  // 向实时区域发送消息
  sendLiveRegionMessage(liveRegion, message) {
    if (!liveRegion) return;
    
    // 清空内容以确保消息被朗读
    liveRegion.textContent = '';
    
    // 强制重新计算布局
    void liveRegion.offsetWidth;
    
    // 设置新消息
    liveRegion.textContent = message;
  }
  
  // 获取可聚焦元素
  getFocusableElements(container = document) {
    if (!container || !(container instanceof Element)) return [];
    
    try {
      return Array.from(container.querySelectorAll(this.focusableElements.join(',')))
        .filter(element => {
          // 确保元素是可见的
          return element.offsetWidth > 0 || element.offsetHeight > 0 || element.getClientRects().length > 0;
        })
        .filter(element => {
          // 确保元素不被禁用
          const disabled = element.getAttribute('disabled') !== null || 
                          element.getAttribute('aria-disabled') === 'true';
          return !disabled;
        });
    } catch (error) {
      console.error('获取可聚焦元素失败:', error);
      return [];
    }
  }
  
  // 聚焦到下一个元素
  focusNextElement(container = document, currentElement = document.activeElement) {
    const focusableElements = this.getFocusableElements(container);
    if (focusableElements.length === 0) return null;
    
    const currentIndex = focusableElements.indexOf(currentElement);
    const nextIndex = currentIndex === -1 || currentIndex === focusableElements.length - 1 ? 0 : currentIndex + 1;
    
    const nextElement = focusableElements[nextIndex];
    try {
      nextElement.focus({ preventScroll: true });
      return nextElement;
    } catch (error) {
      console.error('聚焦到下一个元素失败:', error);
      return null;
    }
  }
  
  // 聚焦到上一个元素
  focusPreviousElement(container = document, currentElement = document.activeElement) {
    const focusableElements = this.getFocusableElements(container);
    if (focusableElements.length === 0) return null;
    
    const currentIndex = focusableElements.indexOf(currentElement);
    const prevIndex = currentIndex === -1 || currentIndex === 0 ? focusableElements.length - 1 : currentIndex - 1;
    
    const prevElement = focusableElements[prevIndex];
    try {
      prevElement.focus({ preventScroll: true });
      return prevElement;
    } catch (error) {
      console.error('聚焦到上一个元素失败:', error);
      return null;
    }
  }
  
  // 聚焦到第一个可聚焦元素
  focusFirstElement(container = document) {
    const focusableElements = this.getFocusableElements(container);
    if (focusableElements.length === 0) return null;
    
    try {
      focusableElements[0].focus({ preventScroll: true });
      return focusableElements[0];
    } catch (error) {
      console.error('聚焦到第一个元素失败:', error);
      return null;
    }
  }
  
  // 聚焦到最后一个可聚焦元素
  focusLastElement(container = document) {
    const focusableElements = this.getFocusableElements(container);
    if (focusableElements.length === 0) return null;
    
    try {
      focusableElements[focusableElements.length - 1].focus({ preventScroll: true });
      return focusableElements[focusableElements.length - 1];
    } catch (error) {
      console.error('聚焦到最后一个元素失败:', error);
      return null;
    }
  }
  
  // 限制焦点在容器内循环
  trapFocus(container, onFocusTrapActivate, onFocusTrapDeactivate) {
    if (!container || !(container instanceof Element)) return null;
    
    // 获取容器内的可聚焦元素
    const focusableElements = this.getFocusableElements(container);
    if (focusableElements.length === 0) return null;
    
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];
    
    // 焦点陷阱处理函数
    const handleFocusTrap = (event) => {
      // 如果按下Tab键且焦点在最后一个元素
      if (event.key === KEY_CODES.TAB && !event.shiftKey && document.activeElement === lastElement) {
        event.preventDefault();
        firstElement.focus({ preventScroll: true });
      }
      // 如果按下Shift+Tab键且焦点在第一个元素
      else if (event.key === KEY_CODES.TAB && event.shiftKey && document.activeElement === firstElement) {
        event.preventDefault();
        lastElement.focus({ preventScroll: true });
      }
    };
    
    // 激活焦点陷阱
    const activateFocusTrap = () => {
      // 保存当前焦点位置
      const previousFocus = document.activeElement;
      
      // 添加键盘事件监听
      container.addEventListener('keydown', handleFocusTrap);
      
      // 将容器设为模态
      container.setAttribute('aria-modal', 'true');
      
      // 聚焦到第一个元素
      firstElement.focus({ preventScroll: true });
      
      // 执行激活回调
      if (typeof onFocusTrapActivate === 'function') {
        onFocusTrapActivate();
      }
      
      // 返回禁用焦点陷阱的函数
      return {
        deactivate: () => {
          // 移除键盘事件监听
          container.removeEventListener('keydown', handleFocusTrap);
          
          // 移除模态属性
          container.removeAttribute('aria-modal');
          
          // 尝试恢复之前的焦点
          try {
            if (previousFocus && previousFocus !== document.body) {
              previousFocus.focus({ preventScroll: true });
            }
          } catch (error) {
            console.error('恢复焦点失败:', error);
          }
          
          // 执行禁用回调
          if (typeof onFocusTrapDeactivate === 'function') {
            onFocusTrapDeactivate();
          }
        }
      };
    };
    
    // 返回激活函数
    return { activate: activateFocusTrap };
  }
  
  // 检查元素是否可聚焦
  isFocusable(element) {
    if (!element || !(element instanceof Element)) return false;
    
    // 检查是否有禁用属性
    if (element.hasAttribute('disabled') || element.getAttribute('aria-disabled') === 'true') {
      return false;
    }
    
    // 检查是否有tabindex="-1"（仍然可聚焦但不在Tab序列中）
    const tabindex = element.getAttribute('tabindex');
    if (tabindex === '-1') {
      return true;
    }
    
    // 检查是否是默认可聚焦元素
    try {
      return this.focusableElements.some(selector => {
        return element.matches(selector);
      });
    } catch (error) {
      console.error('检查元素是否可聚焦失败:', error);
      return false;
    }
  }
  
  // 检查元素是否在Tab序列中
  isInTabOrder(element) {
    if (!element || !(element instanceof Element)) return false;
    
    // 检查是否有禁用属性
    if (element.hasAttribute('disabled') || element.getAttribute('aria-disabled') === 'true') {
      return false;
    }
    
    // 检查tabindex
    const tabindex = element.getAttribute('tabindex');
    if (tabindex === '-1') {
      return false;
    }
    if (tabindex && parseInt(tabindex, 10) > 0) {
      return true;
    }
    
    // 检查是否是默认在Tab序列中的元素
    const tabbableElements = [
      'a[href]',
      'area[href]',
      'input:not([disabled]):not([tabindex="-1"]) [type!="hidden"]',
      'select:not([disabled]):not([tabindex="-1"]) [type!="hidden"]',
      'textarea:not([disabled]):not([tabindex="-1"]) [type!="hidden"]',
      'button:not([disabled]):not([tabindex="-1"]) [type!="hidden"]',
      '[tabindex]:not([tabindex="-1"]) [type!="hidden"]',
      '[contenteditable]:not([tabindex="-1"]) [type!="hidden"]',
      'video[controls]:not([tabindex="-1"]) [type!="hidden"]',
      'audio[controls]:not([tabindex="-1"]) [type!="hidden"]',
      '[role="button"]:not([disabled]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="link"]:not([tabindex="-1"]) [type!="hidden"]',
      '[role="checkbox"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="radio"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="combobox"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="slider"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="spinbutton"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="menu"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="tablist"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="listbox"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="radiogroup"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="application"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="tree"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="grid"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="treegrid"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="option"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="menuitem"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="menuitemcheckbox"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="menuitemradio"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="command"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="separator"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="tab"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]',
      '[role="treeitem"]:not([aria-disabled="true"]):not([tabindex="-1"]) [type!="hidden"]'
    ];
    
    try {
      return tabbableElements.some(selector => {
        return element.matches(selector);
      });
    } catch (error) {
      console.error('检查元素是否在Tab序列中失败:', error);
      return false;
    }
  }
  
  // 获取元素的焦点顺序
  getTabOrder(container = document) {
    const focusableElements = this.getFocusableElements(container);
    
    // 按tabindex排序
    return focusableElements.sort((a, b) => {
      const aTabindex = parseInt(a.getAttribute('tabindex') || '0', 10);
      const bTabindex = parseInt(b.getAttribute('tabindex') || '0', 10);
      
      if (aTabindex > 0 && bTabindex > 0) {
        return aTabindex - bTabindex;
      }
      if (aTabindex > 0) return -1;
      if (bTabindex > 0) return 1;
      
      // 对于tabindex=0或无tabindex的元素，按DOM顺序排序
      return 0;
    });
  }
  
  // 创建键盘快捷键处理函数
  createKeyHandler(keyConfigs) {
    return (event) => {
      const config = keyConfigs.find(config => {
        // 检查修饰键
        if (config.ctrl !== undefined && config.ctrl !== event.ctrlKey) return false;
        if (config.alt !== undefined && config.alt !== event.altKey) return false;
        if (config.shift !== undefined && config.shift !== event.shiftKey) return false;
        if (config.meta !== undefined && config.meta !== event.metaKey) return false;
        
        // 检查键名
        return config.key === event.key || config.code === event.code;
      });
      
      if (config && typeof config.handler === 'function') {
        event.preventDefault();
        event.stopPropagation();
        config.handler(event);
        return true;
      }
      
      return false;
    };
  }
  
  // 模拟点击事件（适用于键盘操作）
  simulateClick(element, options = {}) {
    if (!element || !(element instanceof Element)) return;
    
    const { bubbles = true, cancelable = true, composed = true } = options;
    
    const clickEvent = new MouseEvent('click', {
      bubbles,
      cancelable,
      composed
    });
    
    element.dispatchEvent(clickEvent);
  }
  
  // 创建可访问的错误提示
  createAccessibleError(errorElement, message, options = {}) {
    if (!errorElement) return null;
    
    const { 
      liveRegion = true,
      role = 'alert',
      describedBy = true,
      focus = true
    } = options;
    
    // 设置错误消息
    errorElement.textContent = message;
    
    // 设置错误元素的角色
    errorElement.setAttribute('role', role);
    
    // 设置错误元素的样式（如果需要）
    errorElement.setAttribute('aria-atomic', 'true');
    
    if (liveRegion) {
      errorElement.setAttribute('aria-live', 'assertive');
    }
    
    if (focus) {
      try {
        errorElement.focus({ preventScroll: true });
      } catch (error) {
        console.error('聚焦到错误元素失败:', error);
      }
    }
    
    return errorElement;
  }
  
  // 创建可访问的确认对话框
  createAccessibleDialog(dialogElement, options = {}) {
    if (!dialogElement) return null;
    
    const { 
      title, 
      description,
      modal = true,
      focusTrap = true,
      closeButton,
      onClose
    } = options;
    
    // 设置对话框角色
    dialogElement.setAttribute('role', 'dialog');
    
    // 设置模态属性
    if (modal) {
      dialogElement.setAttribute('aria-modal', 'true');
    }
    
    // 设置标题和描述
    if (title) {
      const titleElement = document.createElement('h2');
      titleElement.textContent = title;
      titleElement.id = `dialog-title-${Date.now()}`;
      dialogElement.prepend(titleElement);
      dialogElement.setAttribute('aria-labelledby', titleElement.id);
    }
    
    if (description) {
      const descElement = document.createElement('p');
      descElement.textContent = description;
      descElement.id = `dialog-desc-${Date.now()}`;
      dialogElement.appendChild(descElement);
      dialogElement.setAttribute('aria-describedby', descElement.id);
    }
    
    // 添加关闭按钮
    if (closeButton && !dialogElement.querySelector('.close-button')) {
      const button = document.createElement('button');
      button.className = 'close-button';
      button.textContent = '关闭';
      button.setAttribute('aria-label', '关闭对话框');
      button.addEventListener('click', () => {
        if (typeof onClose === 'function') {
          onClose();
        }
      });
      dialogElement.appendChild(button);
    }
    
    // 启用焦点陷阱
    let focusTrapController = null;
    if (focusTrap) {
      focusTrapController = this.trapFocus(dialogElement);
    }
    
    // 显示对话框
    dialogElement.style.display = 'block';
    
    // 聚焦到对话框
    if (focusTrapController) {
      focusTrapController.activate();
    } else {
      const firstFocusable = this.getFocusableElements(dialogElement)[0];
      if (firstFocusable) {
        firstFocusable.focus({ preventScroll: true });
      }
    }
    
    // 返回控制器
    return {
      close: () => {
        if (focusTrapController) {
          focusTrapController.deactivate();
        }
        dialogElement.style.display = 'none';
      }
    };
  }
  
  // 验证无障碍性
  validateAccessibility(element) {
    if (!element) return [];
    
    const issues = [];
    
    // 检查图像是否有替代文本
    if (element.tagName === 'IMG' && !element.hasAttribute('alt')) {
      issues.push({
        type: 'error',
        message: '图像缺少alt属性',
        element
      });
    }
    
    // 检查表单元素是否有标签
    const formElements = ['INPUT', 'SELECT', 'TEXTAREA'];
    if (formElements.includes(element.tagName) && !element.hasAttribute('aria-label') && !element.hasAttribute('aria-labelledby')) {
      // 检查是否有相关联的label元素
      const id = element.id;
      const label = id ? document.querySelector(`label[for="${id}"]`) : null;
      if (!label) {
        issues.push({
          type: 'error',
          message: '表单元素缺少标签关联',
          element
        });
      }
    }
    
    // 检查可聚焦元素是否有aria-label或aria-labelledby
    const interactiveRoles = [
      'button', 'link', 'checkbox', 'radio', 'combobox', 'listbox', 'menu',
      'menuitem', 'option', 'tab', 'slider', 'spinbutton', 'switch'
    ];
    
    const role = this.getRole(element);
    if (interactiveRoles.includes(role) && !element.hasAttribute('aria-label') && 
        !element.hasAttribute('aria-labelledby') && !element.textContent.trim()) {
      issues.push({
        type: 'warning',
        message: '交互元素缺少可访问名称',
        element
      });
    }
    
    // 检查aria-hidden="true"元素是否仍然可聚焦
    if (element.hasAttribute('aria-hidden') && element.getAttribute('aria-hidden') === 'true' && 
        this.isFocusable(element)) {
      issues.push({
        type: 'error',
        message: 'aria-hidden="true"元素不应该可聚焦',
        element
      });
    }
    
    return issues;
  }
  
  // 生成无障碍报告
  generateAccessibilityReport(container = document) {
    const report = {
      totalElements: 0,
      issues: {
        errors: 0,
        warnings: 0,
        suggestions: 0
      },
      details: []
    };
    
    // 递归检查所有元素
    const checkElements = (parent) => {
      Array.from(parent.children).forEach(element => {
        report.totalElements++;
        
        const issues = this.validateAccessibility(element);
        if (issues.length > 0) {
          report.details.push(...issues);
          
          // 统计问题类型
          issues.forEach(issue => {
            if (issue.type === 'error') report.issues.errors++;
            else if (issue.type === 'warning') report.issues.warnings++;
            else report.issues.suggestions++;
          });
        }
        
        // 递归检查子元素
        checkElements(element);
      });
    };
    
    checkElements(container);
    
    // 计算无障碍分数
    const totalIssues = report.issues.errors + report.issues.warnings + report.issues.suggestions;
    const baseScore = 100;
    const errorPenalty = report.issues.errors * 5;
    const warningPenalty = report.issues.warnings * 2;
    const suggestionPenalty = report.issues.suggestions * 1;
    
    report.score = Math.max(0, baseScore - errorPenalty - warningPenalty - suggestionPenalty);
    
    return report;
  }
  
  // 提供无障碍帮助信息
  getAccessibilityHelp() {
    return {
      keyboardNavigation: {
        title: '键盘导航帮助',
        shortcuts: [
          { key: 'Tab', description: '导航到下一个可交互元素' },
          { key: 'Shift+Tab', description: '导航到上一个可交互元素' },
          { key: 'Enter', description: '激活按钮、链接或其他交互元素' },
          { key: 'Space', description: '选择复选框或单选按钮' },
          { key: 'Arrow Keys', description: '导航菜单、下拉列表和滑块' },
          { key: 'Esc', description: '关闭弹出窗口或菜单' },
          { key: 'Home', description: '导航到列表或页面的开始' },
          { key: 'End', description: '导航到列表或页面的结尾' },
          { key: 'Ctrl+F', description: '在页面中搜索' },
          { key: 'F1', description: '打开帮助菜单' }
        ]
      },
      screenReader: {
        title: '屏幕阅读器帮助',
        tips: [
          '使用Ctrl+Option+Space（macOS）或Alt+Space（Windows）激活/停用屏幕阅读器',
          '使用箭头键导航页面内容',
          '使用Tab键导航交互元素',
          '按下Enter键激活当前元素',
          '使用Ctrl+Alt+右箭头（macOS）或Alt+右箭头（Windows）导航到下一个区域',
          '使用Ctrl+Alt+左箭头（macOS）或Alt+左箭头（Windows）导航到上一个区域',
          '使用Ctrl+Alt+U（macOS）或Ins+F7（Windows）列出页面中的所有链接'
        ]
      },
      generalTips: {
        title: '无障碍使用提示',
        tips: [
          '确保所有图像都有替代文本描述',
          '为所有表单元素提供清晰的标签',
          '使用足够的颜色对比度确保文本可读性',
          '避免仅依赖颜色传达重要信息',
          '确保所有功能都可以通过键盘访问',
          '为复杂交互提供清晰的提示和反馈',
          '测试您的网站在不同屏幕阅读器中的表现',
          '考虑使用高对比度模式和文本放大功能'
        ]
      }
    };
  }
  
  // 导出无障碍配置
  exportAccessibilityConfig() {
    try {
      const config = accessibilityService.getConfig();
      const dataStr = JSON.stringify(config, null, 2);
      const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
      
      const exportFileDefaultName = 'accessibility-config.json';
      
      const linkElement = document.createElement('a');
      linkElement.setAttribute('href', dataUri);
      linkElement.setAttribute('download', exportFileDefaultName);
      linkElement.click();
      
      return true;
    } catch (error) {
      console.error('导出无障碍配置失败:', error);
      return false;
    }
  }
  
  // 导入无障碍配置
  importAccessibilityConfig(file) {
    return new Promise((resolve, reject) => {
      if (!file) {
        reject(new Error('没有选择文件'));
        return;
      }
      
      const reader = new FileReader();
      
      reader.onload = (event) => {
        try {
          const config = JSON.parse(event.target.result);
          
          // 验证配置格式
          if (typeof config !== 'object' || !config) {
            throw new Error('无效的配置文件格式');
          }
          
          // 应用配置
          Object.assign(accessibilityService.state, config);
          accessibilityService.applySettings();
          
          resolve(config);
        } catch (error) {
          console.error('导入无障碍配置失败:', error);
          reject(error);
        }
      };
      
      reader.onerror = () => {
        reject(new Error('文件读取失败'));
      };
      
      reader.readAsText(file);
    });
  }
}

// 创建工具实例
const accessibilityUtils = new AccessibilityUtils();

// 导出工具实例和常量
export {
  accessibilityUtils,
  ARIA_ROLES,
  ARIA_ATTRIBUTES,
  KEY_CODES
};

// 默认导出
export default accessibilityUtils;